package tq.com.tqteacher.model;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.PublicKey;
import java.util.ArrayList;

public class TQDirectoryModel {

    private String date;
    private ArrayList<TQDirectoryItem> mDirectoryItems = new ArrayList<>();


    static public class TQDirectoryItem{
        private String title;
        private ArrayList<TQFileInfo> mTQFileItems = new ArrayList<>();

        public String getTitle(){
            return title;
        }
        public ArrayList<TQFileInfo> getTQFileItems(){
            return mTQFileItems;
        }

        public String getData(){
            if(mTQFileItems.size() > 0){
                TQFileInfo lInfo = mTQFileItems.get(0);
                return lInfo.getDate();
            }
            return "";
        }
    }
    public ArrayList<TQDirectoryItem> getDirectoryItems(){
        return mDirectoryItems;
    }
    public String getDate(){
        if(date != null){
            return date;
        }

        if(mDirectoryItems.size() == 0) return "";
        TQDirectoryItem lItem = mDirectoryItems.get(0);
        if(lItem.mTQFileItems.size() > 0){
            TQFileInfo lInfo = lItem.getTQFileItems().get(0);
            date = lInfo.getDate();
        }
        return date;
    }

    static public TQDirectoryItem tagFromJson(JSONObject pObject){
        if(pObject == null) return null;
        String tag = pObject.optString("tag");
        JSONArray files = pObject.optJSONArray("file_list");
        if(files == null || files.length() == 0){
            return null;
        }

        TQDirectoryItem lItem = new TQDirectoryItem();
        lItem.title = tag;
        for (int i = 0; i < files.length(); i++){
            try{
                JSONObject lObject = files.getJSONObject(i);
                TQFileInfo lInfo = TQFileInfo.fromJson(lObject);
                if(lInfo != null){
                    lItem.mTQFileItems.add(lInfo);
                }
            }catch (JSONException pE){
                pE.printStackTrace();
            }
        }
        return lItem;
    }

    public boolean isSameDate(TQDirectoryItem pDirectoryItem){
        if(pDirectoryItem == null || pDirectoryItem.getTQFileItems().size() == 0) return true;
        TQFileInfo lInfo = pDirectoryItem.getTQFileItems().get(0);
        String date = lInfo.getDate();

        return this.getDate().equalsIgnoreCase(date);
    }


    public void addTag(TQDirectoryItem  pItem){
        if(pItem == null) return;
        mDirectoryItems.add(pItem);
    }
}
